#! /usr/bin/env python
# -*- coding: UTF-8 -*-

import pygtk
pygtk.require('2.0')
import gtk
import gobject
import gnome
import gnomeapplet
import sys,re

import logging
from datetime import datetime

logging.basicConfig(filename="/tmp/applet.log") # я решил, что простого сохранения в лог мне хватит :)
log = logging.getLogger("KnockKnock")
log.setLevel(logging.INFO)

class KnockKnockApplet(gnomeapplet.Applet):# основной класс
 def update_tooltip(self, text = None):
    if text is None:
        self.tooltip.set_tip(self.applet, self.tooltip_text)
    else:
        self.tooltip_text = text
        self.update_tooltip()
    
 def update_text(self,text=None):
    if text is None:
        self.temp.set_text(self.data)
    else:
        self.data = text
        self.update_text()

 def update_image(self,image_path=None):
    if image_path is None:
        self.itemp.set_from_file(self.idata)
    else:
        self.idata = image_path
        self.update_image()

 def create_applet(self):    # создание апплета, самая смыслонагруженная часть
    app_window = self.applet
    event_box = gtk.EventBox()
    event_box.set_events(gtk.gdk.BUTTON_PRESS_MASK |
        gtk.gdk.POINTER_MOTION_MASK |
        gtk.gdk.POINTER_MOTION_HINT_MASK |
        gtk.gdk.CONFIGURE )

    self._ok_image = "/usr/share/gnome-panel/pixmaps/Knock_KnockApplet/ok.png"
    self._not_image = "/usr/share/gnome-panel/pixmaps/Knock_KnockApplet/not.png"
    self._name = "Knock knock"
    self._description = "Knock knock Applet"
    self._timeout = 10000;
    self._url = "172.16.0.1"
    self._lifeline = re.compile(r"(\d) received") 
 
    self.stat = True # True - Image; False  - Text
    self.inside_applet = gtk.HBox()
  
    if self.stat: 
       self.itemp = gtk.Image()
       self.idata = self._not_image 
       self.update_image()
       self.inside_applet.pack_start(self.itemp)
    else: 
       self.temp = gtk.Label()
       self.data = "TT" # я не стал искать иконку и ограничился надписью TT
       self.update_text()
       self.inside_applet.pack_start(self.temp)
 
    self.tooltip = gtk.Tooltips() # в качестве демонстрации, создадим также всплывающую подсказку
    self.tooltip_text = "Middle click for tooltip update"
    self.update_tooltip()

    event_box.add(self.inside_applet)
    app_window.add(event_box)
    app_window.show_all()
    gobject.timeout_add(self._timeout, self.on_timeout)
    return event_box

 def button_pressed(self, widget, event, *args, **kwargs):
    if event.button==2:# средняя кнопка мыши, обновить подсказку
        self.update_tooltip(datetime.utcnow().strftime("%Y/%m/%d %H:%M:%S"))
        self.update_image(self._ok_image)
    elif event.button==1:# левая кнопка мыши, записать в лог
        log.info("Button Pressed: %s",datetime.utcnow().strftime("%Y/%m/%d %H:%M:%S"))
        self.update_image(self._not_image)
 	
 def on_timeout(self):
		import os
		pingaling = os.popen("ping -q -c2 "+self._url,"r")
		status =-1
		while 1:
			line = pingaling.readline()
		#	print line
			if not line: break
			igot = re.findall(self._lifeline,line)
			if igot:
				status = int(igot[0]) #Nubmer of received packages
		if (status == 2):
				self.update_image(self._ok_image)
		else:
				self.update_image(self_not_image)
		return True

 def __init__(self,applet,iid):
    self.__gobject_init__()
    self.applet = applet

    self.box = self.create_applet()
    self.applet.connect("button-press-event",self.button_pressed) # добавляем обработчик события клика
    log.info("Applet created succesfully")

gobject.type_register(KnockKnockApplet)

DEBUG = False

def knockknock_applet_factory(applet, iid): # Реализация фабрики
	log.info("Creating the applet...")
	KnockKnockApplet(applet, iid)
	return True

log.info("Starting...")
if __name__ == '__main__':
    gobject.type_register(KnockKnockApplet)

    # Use parameter "run-in-window" to just run as a regular
    # application for debugging purposes
    if len(sys.argv) > 1 and sys.argv[1] == '-d':
        # create the main window
        main_window = gtk.Window(gtk.WINDOW_TOPLEVEL)
        main_window.set_title("Hello")
        main_window.connect('destroy', gtk.main_quit)
        main_window.set_default_size(36, 36)

        # create the applet and run in the window
        app = gnomeapplet.Applet()
        knockknock_applet_factory(app, None)
        app.reparent(main_window)

        # run it
        main_window.show_all()
        gtk.main()
    else:
        # create as an applet
	gnomeapplet.bonobo_factory("OAFIID:Knock_KnockApplet_Factory",
                       KnockKnockApplet.__gtype__,
                       "KnockKnock",
                       "0.1",
                       knockknock_applet_factory) # Запуск всего механизма

log.info("Stopping...")
